#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <fcntl.h>
#include <pthread.h>

#include <audio_hpf.h>
#include "testopt.h"
#include "audio_process.h"

#define AUDIO_BUF_SIZE 800

extern TEST_ARGS testArgs;
extern char fileName[NAME_BUF_SIZE];


static char inFileName[256] = "test_hpf.pcm";
static char outFileName[256] = "test_hpf_result.pcm";

static int sampleRate = 16000;

FilterState handle_ao_hpf;

static void *audio_HPF_thread(void *argv)
{
	char *srcName = inFileName;
	char *dstName = outFileName;

	FILE *fpSrc = fopen(srcName,"r");
	FILE *fpDst = fopen(dstName,"w");

	if(NULL == fpSrc||NULL == fpDst) {
		printf("open file %s or %s failed\n",srcName,dstName);
		return NULL;
	}

	unsigned char *pcm_buf = NULL;
	pcm_buf = (unsigned char*)malloc(AUDIO_BUF_SIZE);
	if (NULL == pcm_buf){
		printf("malloc pcm_buf space failed\n");
		return NULL;
	}

	int ret = -1;
	ret = InitializeFilter(&handle_ao_hpf,sampleRate);
	if (ret != 0) {
		printf("Hpf InitializeFilter error.\n");
		return NULL;
	} else {
		printf("Hpf InitializeFilter OK.\n");
	}
	int size = 0;

	while(1){
		size = fread(pcm_buf,1,AUDIO_BUF_SIZE,fpSrc);
		printf("size = %d\n",size);
		if (size < AUDIO_BUF_SIZE){
			break;
		}

		ret = IngenicHPF_Filter(&handle_ao_hpf,(short*)pcm_buf,size);
		if (ret != 0){
			printf("InitializeFilter error.\n");
			return NULL;
		}
		fwrite(pcm_buf,1,size,fpDst);
	}

	free(pcm_buf);
	fclose(fpSrc);
	fclose(fpDst);

	pcm_buf = NULL;
	fpSrc = NULL;
	fpDst = NULL;

	pthread_exit(0);
}

static void set_hpfTest_param(TEST_ARGS *pTestArgs)
{
	if(NULL == pTestArgs) {
		printf("fun:%s,pTestArgs is empty.\n",__func__);
		return;
	}
	if(strcmp(pTestArgs->inFileName,"") != 0)
		strncpy(inFileName,pTestArgs->inFileName,MAX_FILE_NAME_LEN);

	if(strcmp(pTestArgs->outFileName,"") != 0)
		strncpy(outFileName,pTestArgs->outFileName,MAX_FILE_NAME_LEN);

	if(pTestArgs->sampleRate > 0)
		sampleRate = pTestArgs->sampleRate;
}

int main(int argc,char *argv[])
{
	int ret = -1;

	ret = parse_param(argc,argv);
	if(1 == ret) {
		return 0;
	}
	if(ret < 0) {
		printf("parse_param failed.\n");
		return -1;
	} else {
		printf("parse_param Ok.\n");
	}

	set_hpfTest_param(&testArgs);

	printf("This test parameter are as follows:\n\n");
	printf("inFileName = %s\n",inFileName);
	printf("outFileName = %s\n",outFileName);

	printf("[INFO]:Start to audio HPF test\n");
	printf("[INFO]:Please input any key to continue.\n");
	getchar();

	pthread_t hpf_thread_id;
	ret = pthread_create(&hpf_thread_id,NULL,audio_HPF_thread,NULL);
	if(ret != 0) {
		printf("create audio_HPF_thread failed\n");
		return -1;
	}

	pthread_join(hpf_thread_id,NULL);
	printf("Finished hpf thread.\n");

	return 0;
}

